<?php
/* ========== ########## ========== ########## ========== ########## ========== */
/*                                                                              */
/*   WHMCS v4.1.2 NULLED R4 by FLIPMODE  [ BAD SYNTAX ]                         */
/*                                                                              */
/*                             INTERNAL BAD SYNTAX NULLED VERSION: 2.5.9.6 R4   */
/*                                                                              */
/*   ALL files have been analysed, cleaned and nulled of:                       */
/*     - Call Backs  (100%)                                                     */
/*     - Link Backs (95%)                                                       */
/*     - Licensing  (100%)                                                      */
/*     - Remote Links + URL's                                                   */
/*                                                                              */
/*   WHMCS v4.1.2 RELEASED: 4th November 2009                                   */
/*    -> FIRST v4.1.2 NULL R1: 19th November 2009                               */
/*    -> UPDATED v4.1.2 NULL R4: 27th November 2009                             */
/*                                                                              */
/*   TESTING + VERIFICATION::                                                   */
/*     Files Cleaned, Nulled, Checked, Verified By:                             */
/*      -> FLIPMODE!                                                            */
/*     Decoded By:                                                              */
/*      -> FLIPMODE! + Unknown Decoder                                          */
/*     Tested By:                                                               */
/*      -> FLIPMODE!, LeetWolf, and 12 Anonymous Users...                       */
/*     WHMCS 4.1.2 Supplied By:                                                 */
/*      -> WHM CompleteShit Coder @ WHMCS.com                                   */
/*                                                                              */
/*                                                                              */
/*   IMPORTANT NOTE::                                                           */
/*   PLEASE NOTE THIS IS FOR TRIAL PURPOSES ONLY!                               */
/*                          LIKE IT? THEN BUY IT!                               */
/*                                                                              */
/* ========== ########## ========== ########## ========== ########## ========== */


require dirname (__FILE__) . '/../dbconnect.php';
include ROOTDIR . '/includes/functions.php';
include ROOTDIR . '/includes/clientfunctions.php';
include ROOTDIR . '/includes/modulefunctions.php';
include ROOTDIR . '/includes/gatewayfunctions.php';
include ROOTDIR . '/includes/ccfunctions.php';
include ROOTDIR . '/includes/processinvoices.php';
include ROOTDIR . '/includes/invoicefunctions.php';
include ROOTDIR . '/includes/backupfunctions.php';
include ROOTDIR . '/includes/ticketfunctions.php';
include ROOTDIR . '/includes/currencyfunctions.php';
@ini_set ('memory_limit', '512M');
@ini_set ('max_execution_time', 0);
@set_time_limit (0);
$licensing->incronrun = true;
$licensing->decodeLocal ();
$escalations = '';
if (($_SERVER['argv'][1] == 'escalations' OR $_GET['escalations']))
{
	$escalations = true;
}

if ($escalations)
{
	include ROOTDIR . '/includes/adminfunctions.php';
	$lastruntime = $CONFIG['TicketEscalationLastRun'];
	$result = select_query ('tblticketescalations', '', '');
	while ($data = mysql_fetch_array ($result))
	{
		$id = $data['id'];
		$name = $data['name'];
		$departments = $data['departments'];
		$statuses = $data['statuses'];
		$priorities = $data['priorities'];
		$timeelapsed = $data['timeelapsed'];
		$newdepartment = $data['newdepartment'];
		$newpriority = $data['newpriority'];
		$newstatus = $data['newstatus'];
		$flagto = $data['flagto'];
		$notify = $data['notify'];
		$addreply = $data['addreply'];
		$ticketsqry = 'SELECT * FROM tbltickets WHERE ';
		if ($departments)
		{
			$ticketsqry .= '' . 'did IN (' . $departments . ') AND ';
		}

		if ($statuses)
		{
			$ticketsqry .= 'status IN (\'' . str_replace (',', '\',\'', $statuses) . '\') AND ';
		}

		if ($priorities)
		{
			$ticketsqry .= 'urgency IN (\'' . str_replace (',', '\',\'', $priorities) . '\') AND ';
		}

		if ($timeelapsed)
		{
			$tickettime = date ('Y-m-d H:i:s', mktime (date ('H'), date ('i') - $timeelapsed, date ('s'), date ('m'), date ('d'), date ('Y')));
			$ticketlasttime = date ('Y-m-d H:i:s', strtotime ('' . $lastruntime . ' - ' . $timeelapsed . ' minutes'));
			$ticketsqry .= '' . 'lastreply>\'' . $ticketlasttime . '\' AND lastreply<=\'' . $tickettime . '\' AND ';
		}

		$ticketsqry = substr ($ticketsqry, 0, 0 - 5);
		$result2 = full_query ($ticketsqry);
		while ($data = mysql_fetch_array ($result2))
		{
			$ticketid = $data['id'];
			$tickettid = $data['tid'];
			$ticketsubject = $data['title'];
			$ticketuserid = $data['userid'];
			$ticketfromname = $data['name'];
			$ticketdeptid = $data['did'];
			$ticketpriority = $data['urgency'];
			$ticketstatus = $data['status'];
			$updateqry = array ();
			if ($newdepartment)
			{
				$updateqry['did'] = $newdepartment;
			}

			if ($newpriority)
			{
				$updateqry['urgency'] = $newpriority;
			}

			if ($newstatus)
			{
				$updateqry['status'] = $newstatus;
			}

			if ($flagto)
			{
				$updateqry['flag'] = $flagto;
			}

			if (count ($updateqry))
			{
				update_query ('tbltickets', $updateqry, array ('id' => $ticketid));
			}

			if ($notify)
			{
				if ($ticketuserid)
				{
					$result3 = select_query ('tblclients', 'firstname,lastname', array ('id' => $ticketuserid));
					$data = mysql_fetch_array ($result3);
					$clientname = $data['firstname'] . ' ' . $data['lastname'];
				}
				else
				{
					$clientname = $ticketfromname;
				}

				$deptname = getdepartmentname ($ticketdeptid);
				if ($newdepartment)
				{
					$ticketdeptid = $newdepartment;
				}

				sendadminnotification ('support', '' . '[Ticket ID: ' . $tickettid . '] Escalation Rule Notification', '' . '<p>The escalation rule ' . $name . ' has just been applied to this ticket.</p><p>Client: ' . $clientname . '<br>Department: ' . $deptname . '<br>Subject: ' . $ticketsubject . '<br>Priority: ' . $ticketpriority . '<br>Status: ' . $ticketstatus . '</p><p>You can respond to this ticket by simply replying to this email or by logging into the administration area.</p>', $ticketdeptid);
			}

			if ($addreply)
			{
				if (!$newstatus)
				{
					$newstatus = $ticketstatus;
				}

				addreply ($ticketid, '', $addreply, true, '', '', $newstatus);
				continue;
			}
		}
	}

	update_query ('tblconfiguration', array ('value' => date ('Y-m-d H:i:s')), array ('setting' => 'TicketEscalationLastRun'));
	logactivity ('Cron Job: Escalation Rules Run');
	exit ();
}

$cronreport = 'Cron Job Report for ' . date ('d-m-Y H:i:s') . '<br><br>';
logactivity ('Cron Job: Starting');
if ($CONFIG['CurrencyAutoUpdateExchangeRates'])
{
	logactivity ('Cron Job: Updating Currency Exchange Rates');
	$cronreport .= 'Updated Currency Exchange Rates<br>';
	$cronreport .= currencyupdaterates ();
	$cronreport .= '<br>';
}

if ($CONFIG['CurrencyAutoUpdateProductPrices'])
{
	logactivity ('Cron Job: Updating Product Pricing for Current Exchange Rates');
	currencyupdatepricing ();
	$cronreport .= 'Updated Product Pricing for Current Exchange Rates<br><br>';
}

logactivity ('Cron Job: Generating Invoices');
createinvoices ();
logactivity ('Cron Job: Adding Late Fees');
invoicesaddlatefee ();
if (!$disableccprocessing)
{
	logactivity ('Cron Job: Credit Card Processing');
	ccprocessing ();
}

logactivity ('Cron Job: Sending Invoice Reminders');
sendoverdueinvoicereminders ();
if ($CONFIG['SendReminder'] == 'on')
{
	$reminders = '';
	if ($CONFIG['SendInvoiceReminderDays'])
	{
		$invoicedateyear = date ('Ymd', mktime (0, 0, 0, date ('m'), date ('d') + $CONFIG['SendInvoiceReminderDays'], date ('Y')));
		$query = 'SELECT * FROM tblinvoices WHERE duedate=\'' . $invoicedateyear . '\' AND `status`=\'Unpaid\'';
		$result = full_query ($query);
		$i = 0;
		while ($data = mysql_fetch_array ($result))
		{
			$id = $data['id'];
			sendmessage ('Invoice Payment Reminder', $id);
			++$i;
		}

		$cronreport .= '' . $i . ' Invoice Payment Reminders Sent<br><br>';
	}
}

$renewalsnoticescount = 0;
$renewals = explode (',', $CONFIG['DomainRenewalNotices']);
logactivity ('Cron Job: Sending Domain Renewal Notices');
foreach ($renewals as $renewal)
{
	if ($renewal)
	{
		$renewaldate = date ('Y-m-d', mktime (0, 0, 0, date ('m'), date ('d') + $renewal, date ('Y')));
		$query = '' . 'SELECT * FROM tbldomains WHERE status=\'Active\' AND nextduedate=\'' . $renewaldate . '\' AND recurringamount!=\'0.00\'';
		$result = full_query ($query);
		while ($data = mysql_fetch_array ($result))
		{
			$domainid = $data['id'];
			sendmessage ('Upcoming Domain Renewal Notice', $domainid);
			++$renewalsnoticescount;
		}

		continue;
	}
}

$cronreport .= '' . $renewalsnoticescount . ' Upcoming Domain Renewal Notices Sent<br><br>';
if ($CONFIG['AutoSuspension'] == 'on')
{
	update_query ('tblhosting', array ('overideautosuspend' => ''), 'overideautosuspend=\'on\' AND overidesuspenduntil<\'' . date ('Y-m-d') . '\' AND overidesuspenduntil!=\'0000-00-00\'');
	$suspended = '';
	$i = 0;
	$suspenddate = date ('Ymd', mktime (0, 0, 0, date ('m'), date ('d') - $CONFIG['AutoSuspensionDays'], date ('Y')));
	$query3 = '' . 'SELECT * FROM tblhosting WHERE domainstatus=\'Active\' AND billingcycle!=\'Free Account\' AND billingcycle!=\'One Time\' AND overideautosuspend!=\'on\' AND nextduedate<=\'' . $suspenddate . '\' ORDER BY domain ASC';
	$result3 = full_query ($query3);
	while ($data = mysql_fetch_array ($result3))
	{
		$id = $data['id'];
		$userid = $data['userid'];
		$domain = $data['domain'];
		$packageid = $data['packageid'];
		$result2 = select_query ('tblclients', '', array ('id' => $userid));
		$data2 = mysql_fetch_array ($result2);
		$firstname = $data2['firstname'];
		$lastname = $data2['lastname'];
		$groupid = $data2['groupid'];
		$result2 = select_query ('tblproducts', 'servertype', array ('id' => $packageid));
		$data2 = mysql_fetch_array ($result2);
		$module = $data2['servertype'];
		$result2 = select_query ('tblclientgroups', 'susptermexempt', array ('id' => $groupid));
		$data2 = mysql_fetch_array ($result2);
		$susptermexempt = $data2['susptermexempt'];
		if (!$susptermexempt)
		{
			$serverresult = 'No Module';
			logactivity ('' . 'Cron Job: Suspending Service - Service ID: ' . $id);
			if (file_exists (ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php')))
			{
				require_once ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php');
				$serverresult = serversuspendaccount ($id);
			}

			if ($serverresult == 'success')
			{
				sendmessage ('Account Suspended', $id);
				$suspended .= '' . ' - Suspended Service: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Service ID: ' . $id . ' - User ID: ' . $userid . ')<br>';
				++$i;
				continue;
			}
			else
			{
				$suspended .= '' . ' - Manual Suspend Required: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Service ID: ' . $id . ' - User ID: ' . $userid . ' - Error: ' . $serverresult . ')<br>';
				continue;
			}

			continue;
		}
	}

	$query3 = '' . 'SELECT * FROM tblhostingaddons WHERE status=\'Active\' AND billingcycle!=\'Free\' AND billingcycle!=\'One Time\' AND nextduedate<=\'' . $suspenddate . '\' ORDER BY name ASC';
	$result3 = full_query ($query3);
	while ($data = mysql_fetch_array ($result3))
	{
		$id = $data['id'];
		$hostingid = $data['hostingid'];
		$name = $data['name'];
		$nextduedate = $data['nextduedate'];
		$result2 = select_query ('tblhosting', '', array ('id' => $hostingid));
		$data2 = mysql_fetch_array ($result2);
		$userid = $data2['userid'];
		$result2 = select_query ('tblclients', '', array ('id' => $userid));
		$data2 = mysql_fetch_array ($result2);
		$firstname = $data2['firstname'];
		$lastname = $data2['lastname'];
		$groupid = $data2['groupid'];
		$result2 = select_query ('tblclientgroups', 'susptermexempt', array ('id' => $groupid));
		$data2 = mysql_fetch_array ($result2);
		$susptermexempt = $data2['susptermexempt'];
		if (!$susptermexempt)
		{
			update_query ('tblhostingaddons', array ('status' => 'Suspended'), array ('id' => $id));
			$suspended .= '' . ' - Suspended Addon: ' . $firstname . ' ' . $lastname . ' - ' . $name . ' (Service ID: ' . $hostingid . ' - Addon ID: ' . $id . ')<br>';
			logactivity ('' . 'Cron Job: Suspending Addon - Service ID: ' . $hostingid . ' - Addon ID: ' . $id);
			++$i;
			continue;
		}
	}

	$cronreport .= '' . $i . ' Services Suspended<br>';
	if ($suspended != '')
	{
		$cronreport .= $suspended . '<br>';
	}
	else
	{
		$cronreport .= '<br>';
	}
}

if ($CONFIG['AutoTermination'] == 'on')
{
	$terminated = '';
	$i = 0;
	$terminatedate = date ('Ymd', mktime (0, 0, 0, date ('m'), date ('d') - $CONFIG['AutoTerminationDays'], date ('Y')));
	$query = '' . 'SELECT * FROM tblhosting WHERE (domainstatus=\'Active\' OR domainstatus=\'Suspended\') AND billingcycle!=\'Free Account\' AND billingcycle!=\'One Time\' AND nextduedate<=\'' . $terminatedate . '\' AND overideautosuspend!=\'on\' ORDER BY domain ASC';
	$result = full_query ($query);
	while ($data = mysql_fetch_array ($result))
	{
		$id = $data['id'];
		$userid = $data['userid'];
		$domain = $data['domain'];
		$packageid = $data['packageid'];
		$result2 = select_query ('tblclients', '', array ('id' => $userid));
		$data2 = mysql_fetch_array ($result2);
		$firstname = $data2['firstname'];
		$lastname = $data2['lastname'];
		$groupid = $data2['groupid'];
		$result2 = select_query ('tblproducts', 'servertype', array ('id' => $packageid));
		$data2 = mysql_fetch_array ($result2);
		$module = $data2['servertype'];
		$result2 = select_query ('tblclientgroups', 'susptermexempt', array ('id' => $groupid));
		$data2 = mysql_fetch_array ($result2);
		$susptermexempt = $data2['susptermexempt'];
		if (!$susptermexempt)
		{
			$serverresult = 'No Module';
			logactivity ('' . 'Cron Job: Terminating Service - Service ID: ' . $id);
			if (file_exists (ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php')))
			{
				require_once ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php');
				$serverresult = serverterminateaccount ($id);
			}

			if ($serverresult == 'success')
			{
				$terminated .= '' . ' - Terminated Service: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Service ID: ' . $id . ' - User ID: ' . $userid . ')<br>';
				++$i;
				continue;
			}
			else
			{
				$terminated .= '' . ' - Manual Terminate Required: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Service ID: ' . $id . ' - User ID: ' . $userid . ' - Error: ' . $serverresult . ')<br>';
				continue;
			}

			continue;
		}
	}

	$cronreport .= '' . $i . ' Services Terminated<br>';
	if ($terminated != '')
	{
		$cronreport .= $terminated . '<br>';
	}
	else
	{
		$cronreport .= '<br>';
	}
}

if ($CONFIG['AutoCancellationRequests'] == 'on')
{
	$terminated = '';
	$i = 0;
	$terminatedate = date ('Ymd', mktime (0, 0, 0, date ('m'), date ('d'), date ('Y')));
	$query = '' . 'SELECT * FROM tblcancelrequests INNER JOIN tblhosting ON tblhosting.id = tblcancelrequests.relid WHERE (domainstatus!=\'Terminated\' AND domainstatus!=\'Cancelled\') AND (type=\'Immediate\' OR ( type=\'End of Billing Period\' AND nextduedate<=\'' . $terminatedate . '\' ) ) ORDER BY domain ASC';
	$result = full_query ($query);
	while ($data = mysql_fetch_array ($result))
	{
		$id = $data['id'];
		$userid = $data['userid'];
		$domain = $data['domain'];
		$nextduedate = $data['nextduedate'];
		$packageid = $data['packageid'];
		$regdate = frommysqldate ($regdate);
		$nextduedate = frommysqldate ($nextduedate);
		$query2 = '' . 'SELECT * FROM tblclients WHERE id=\'' . $userid . '\'';
		$result2 = full_query ($query2);
		$data2 = mysql_fetch_array ($result2);
		$firstname = $data2['firstname'];
		$lastname = $data2['lastname'];
		$query2 = '' . 'SELECT servertype FROM tblproducts WHERE id=\'' . $packageid . '\'';
		$result2 = full_query ($query2);
		$data2 = mysql_fetch_array ($result2);
		$module = $data2['servertype'];
		$serverresult = 'No Module';
		logactivity ('' . 'Cron Job: Processing Cancellation Request - Service ID: ' . $id);
		if (file_exists (ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php')))
		{
			require_once ROOTDIR . ('' . '/modules/servers/' . $module . '/' . $module . '.php');
			$serverresult = serverterminateaccount ($id);
		}

		if ($serverresult == 'success')
		{
			update_query ('tblhosting', array ('domainstatus' => 'Cancelled'), array ('id' => $id));
			update_query ('tblhostingaddons', array ('status' => 'Cancelled'), array ('hostingid' => $id));
			$terminated .= '' . ' - Automatically Cancelled Service: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Due Date: ' . $nextduedate . ')<br>';
			++$i;
			continue;
		}
		else
		{
			$terminated .= '' . ' - Manual Cancellation Required: ' . $firstname . ' ' . $lastname . ' - ' . $domain . ' (Due Date: ' . $nextduedate . ')<br>';
			continue;
		}
	}

	$cronreport .= '' . $i . ' Cancellation Requests Automatically Processed<br>';
	if ($terminated != '')
	{
		$cronreport .= $terminated . '<br>';
	}
	else
	{
		$cronreport .= '<br>';
	}
}

logactivity ('Cron Job: Closing Inactive Support Tickets');
closeinactivetickets ();
if ($CONFIG['AffiliatesDelayCommission'])
{
	logactivity ('Cron Job: Processing Delayed Affiliate Commissions');
	$affiliatepaymentscleared = 0;
	$query = 'SELECT * FROM tblaffiliatespending WHERE clearingdate<=\'' . date ('Y-m-d') . '\'';
	$result = full_query ($query);
	while ($data = mysql_fetch_array ($result))
	{
		$affaccid = $data['affaccid'];
		$amount = $data['amount'];
		$query2 = '' . 'SELECT * FROM tblaffiliatesaccounts WHERE id=\'' . $affaccid . '\'';
		$result2 = full_query ($query2);
		$data = mysql_fetch_array ($result2);
		$affaccid = $data['id'];
		$relid = $data['relid'];
		$affid = $data['affiliateid'];
		$query2 = '' . 'SELECT domainstatus FROM tblhosting WHERE id=\'' . $relid . '\'';
		$result2 = full_query ($query2);
		$data = mysql_fetch_array ($result2);
		$domainstatus = $data['domainstatus'];
		if (($affaccid AND $domainstatus == 'Active'))
		{
			$query2 = '' . 'UPDATE tblaffiliates SET balance=balance+' . $amount . ' WHERE id=\'' . $affid . '\'';
			$result2 = full_query ($query2);
			$query2 = '' . 'UPDATE tblaffiliatesaccounts SET lastpaid=now() WHERE id=\'' . $affaccid . '\'';
			$result2 = full_query ($query2);
			$query2 = '' . 'INSERT INTO tblaffiliateshistory (affiliateid,date,affaccid,amount) VALUES (\'' . $affid . '\',now(),\'' . $affaccid . '\',\'' . $amount . '\')';
			$result2 = full_query ($query2);
			++$affiliatepaymentscleared;
			continue;
		}
	}

	$cronreport .= '' . $affiliatepaymentscleared . ' Pending Affiliate Payments Made<br><br>';
	$query = 'DELETE FROM tblaffiliatespending WHERE clearingdate<=\'' . date ('Y-m-d') . '\'';
	$result = full_query ($query);
}

if ($CONFIG['SendAffiliateReportMonthly'] == 'on')
{
	if (date ('d') == '1')
	{
		logactivity ('Cron Job: Sending Monthly Affiliate Reports');
		$query = 'SELECT aff.* FROM tblaffiliates aff join tblclients client on aff.clientid = client.id where client.status = \'Active\'';
		$result = full_query ($query);
		while ($data = mysql_fetch_array ($result))
		{
			$id = $data['id'];
			sendmessage ('Affiliate Monthly Referrals Report', $id);
		}

		$cronreport .= 'Monthly Affiliate Earnings Reports Sent to Affiliates<br><br>';
	}
}

if (date ('d') == $CONFIG['CCDaySendExpiryNotices'])
{
	logactivity ('Cron Job: Sending Credit Card Expiry Notices');
	$expiryemailcount = 0;
	$expirymonth = date ('my', mktime (0, 0, 0, date ('m'), date ('d'), date ('Y')));
	$query = '' . 'SELECT id FROM tblclients WHERE AES_DECRYPT(expdate,\'54X6zoYZZnS35o6m5gEwGmYC6' . $cc_encryption_hash . '\')=\'' . $expirymonth . '\' AND status=\'Active\'';
	$result = full_query ($query);
	while ($data = mysql_fetch_array ($result))
	{
		$id = $data['id'];
		sendmessage ('Credit Card Expiring Soon', $id);
		update_query ('tblclients', array ('cardtype' => '', 'cardnum' => '', 'expdate' => '', 'issuenumber' => '', 'startdate' => ''), array ('id' => $id));
		++$expiryemailcount;
	}

	$cronreport .= '' . $expiryemailcount . ' Credit Card Expiration Notices Sent<br><br>';
}

if ($CONFIG['UpdateStatsAuto'] == 'on')
{
	logactivity ('Cron Job: Running Usage Stats Update');
	serverusageupdate ();
	$cronreport .= 'Disk & Bandwidth Usage Statistics Updated<br><br>';
}

$overagesbillingdate = date ('Ymd', mktime (0, 0, 0, date ('m') + 1, 0, date ('Y')));
if ($overagesbillingdate == date ('Ymd'))
{
	logactivity ('Cron Job: Calculating Overages Billing');
	if (!function_exists ('ModuleBuildParams'))
	{
		require ROOTDIR . '/includes/modulefunctions.php';
	}

	$invoiceaction = $CONFIG['OverageBillingMethod'];
	if (!$invoiceaction)
	{
		$invoiceaction = '1';
	}

	$result = select_query ('tblproducts', '', array ('overagesenabled' => '1'));
	while ($data = mysql_fetch_array ($result))
	{
		$pid = $data['id'];
		$prodname = $data['name'];
		$overagesdisklimit = $data['overagesdisklimit'];
		$overagesbwlimit = $data['overagesbwlimit'];
		$overagesbasediskprice = $data['overagesdiskprice'];
		$overagesbasebwprice = $data['overagesbwprice'];
		$result2 = select_query ('tblhosting', 'tblhosting.*,tblclients.currency', array ('packageid' => $pid), '', '', '', 'tblclients ON tblclients.id=tblhosting.userid');
		while ($data = mysql_fetch_array ($result2))
		{
			$serviceid = $data['id'];
			$userid = $data['userid'];
			$currency = $data['currency'];
			$domain = $data['domain'];
			$diskusage = $data['diskusage'];
			$disklimit = $data['disklimit'];
			$bwusage = $data['bwusage'];
			$bwlimit = $data['bwlimit'];
			$result3 = select_query ('tblcurrencies', 'rate', array ('id' => $currency));
			$data = mysql_fetch_array ($result3);
			$convertrate = $data['rate'];
			if (!$convertrate)
			{
				$convertrate = 1;
			}

			$overagesdiskprice = $overagesbasediskprice * $convertrate;
			$overagesbwprice = $overagesbasebwprice * $convertrate;
			$moduleparams = modulebuildparams ($serviceid);
			$thisoveragesdisklimit = $overagesdisklimit;
			$thisoveragesbwlimit = $overagesbwlimit;
			if ($moduleparams['customfields']['Disk Space'])
			{
				$thisoveragesdisklimit = $moduleparams['customfields']['Disk Space'];
			}

			if ($moduleparams['customfields']['Bandwidth'])
			{
				$thisoveragesbwlimit = $moduleparams['customfields']['Bandwidth'];
			}

			if ($moduleparams['configoptions']['Disk Space'])
			{
				$thisoveragesdisklimit = $moduleparams['configoptions']['Disk Space'];
			}

			if ($moduleparams['configoptions']['Bandwidth'])
			{
				$thisoveragesbwlimit = $moduleparams['configoptions']['Bandwidth'];
			}

			$diskoverage = $diskusage - $thisoveragesdisklimit;
			$bwoverage = $bwusage - $thisoveragesbwlimit;
			$overagedesc = $prodname;
			if ($domain)
			{
				$overagedesc .= ' - ' . $domain;
			}

			$overagedesc .= ' (' . date ('01/m/Y - d/m/Y') . ') ';
			getuserslang ($userid);
			if (($thisoveragesdisklimit AND 0 < $diskoverage))
			{
				if ($diskoverage < 0)
				{
					$diskoverage = 0;
				}

				$diskoverage = round ($diskoverage, 2);
				$diskoveragedesc = $overagedesc . '
' . $_LANG['overagestotaldiskusage'] . ('' . ' = ' . $diskusage . ' MB - ') . $_LANG['overagescharges'] . ('' . ' = ' . $diskoverage . ' MB @ ' . $overagesdiskprice . '/MB');
				$diskoverageamount = $diskoverage * $overagesdiskprice;
				insert_query ('tblbillableitems', array ('userid' => $userid, 'description' => $diskoveragedesc, 'amount' => $diskoverageamount, 'recur' => 0, 'recurcycle' => 0, 'recurfor' => 0, 'invoiceaction' => $invoiceaction, 'duedate' => date ('Y-m-d')));
			}

			if (($thisoveragesbwlimit AND 0 < $bwoverage))
			{
				if ($bwoverage < 0)
				{
					$bwoverage = 0;
				}

				$bwoverage = round ($bwoverage, 2);
				$bwoveragedesc = $overagedesc . '
' . $_LANG['overagestotalbwusage'] . ('' . ' = ' . $bwusage . ' MB - ') . $_LANG['overagescharges'] . ('' . ' = ' . $bwoverage . ' MB @ ' . $overagesbwprice . '/MB');
				$bwoverageamount = $bwoverage * $overagesbwprice;
				insert_query ('tblbillableitems', array ('userid' => $userid, 'description' => $bwoveragedesc, 'amount' => $bwoverageamount, 'recur' => 0, 'recurcycle' => 0, 'recurfor' => 0, 'invoiceaction' => $invoiceaction, 'duedate' => date ('Y-m-d')));
				continue;
			}
		}
	}

	$cronreport .= 'Overage Billing Processed<br> - ';
	createinvoices ();
	$cronreport .= '<br><br>';
}

if ($debug_output)
{
	echo '' . '<p>' . $cronreport . '</p>';
}

$query = 'UPDATE tbldomains SET status=\'Expired\' WHERE expirydate<\'' . date ('Y-m-d') . '\' AND expirydate!=\'00000000\' AND status=\'Active\'';
$result = full_query ($query);
logactivity ('Cron Job: Completed');
sendadminnotification ('system', 'Cron Job Activity', $cronreport);
run_hook ('DailyCronJob', array ());
$backupdata = '';
if (($CONFIG['DailyEmailBackup'] OR $CONFIG['FTPBackupHostname']))
{
	logactivity ('Cron Job: Starting Backup Generation');
	$backupdata = generatebackup ();
	logactivity ('Cron Job: Backup Generation Completed');
}

if ($CONFIG['DailyEmailBackup'])
{
	$mail = new PHPMailer ();
	$mail->From = $CONFIG['SystemEmailsFromEmail'];
	$mail->FromName = $CONFIG['SystemEmailsFromName'];
	$mail->Subject = 'MySQL Database Backup';
	if ($CONFIG['MailType'] == 'mail')
	{
		$mail->Mailer = 'mail';
	}
	else
	{
		if ($CONFIG['MailType'] == 'smtp')
		{
			$mail->IsSMTP ();
			$mail->Host = $CONFIG['SMTPHost'];
			$mail->Port = $CONFIG['SMTPPort'];
			$mail->Hostname = $_SERVER['SERVER_NAME'];
			if ($CONFIG['SMTPSSL'])
			{
				$mail->SMTPSecure = 'ssl';
			}

			if ($CONFIG['SMTPUsername'])
			{
				$mail->SMTPAuth = true;
				$mail->Username = $CONFIG['SMTPUsername'];
				$mail->Password = $CONFIG['SMTPPassword'];
			}

			$mail->Sender = $mail->From;
		}
	}

	if ($smtp_debug)
	{
		$mail->SMTPDebug = true;
	}

	$mail->Body = 'Backup File Attached';
	$mail->AddAddress ($CONFIG['DailyEmailBackup']);
	$mail->AddStringAttachment ($backupdata, $db_name . '_backup_' . date ('Ymd_His') . '.zip');
	if ($mail->Send ())
	{
		logactivity ('Cron Job: Daily Email Backup - Sent Successfully');
	}
	else
	{
		logactivity ('Cron Job: Daily Email Backup - Sending Failed - ' . $mail->ErrorInfo);
	}

	$mail->ClearAddresses ();
}

if ($CONFIG['FTPBackupHostname'])
{
	$ftp_server = $CONFIG['FTPBackupHostname'];
	$ftp_user = $CONFIG['FTPBackupUsername'];
	$ftp_pass = $CONFIG['FTPBackupPassword'];
	$ftp_filename = $CONFIG['FTPBackupDestination'] . $db_name . '_backup_' . date ('Ymd_His') . '.zip';
	($ftpconnection = ftp_connect ($ftp_server) OR $error = '' . 'Couldn\'t connect to ' . $ftp_server);
	if (!ftp_login ($ftpconnection, $ftp_user, $ftp_pass))
	{
		logactivity ('Cron Job: Daily FTP Backup - Login Failed');
		exit ();
	}

	$tmp = tmpfile ();
	fwrite ($tmp, $backupdata);
	fseek ($tmp, 0);
	$upload = ftp_fput ($ftpconnection, $ftp_filename, $tmp, FTP_BINARY);
	if (!$upload)
	{
		logactivity ('Cron Job: Daily FTP Backup - Uploading Failed');
		exit ();
	}

	fclose ($tmp);
	ftp_close ($ftpconnection);
	logactivity ('Cron Job: Daily FTP Backup - Completed Successfully');
}

?>